package com.ly.learn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ly.learn.entity.CmsSysPermission;
import com.ly.learn.mapper.CmsSysPermissionMapper;
import com.ly.learn.service.ICmsSysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ly
 * @since 2023-12-21
 */
@Service
public class CmsSysPermissionServiceImpl extends ServiceImpl<CmsSysPermissionMapper, CmsSysPermission> implements ICmsSysPermissionService {

    @Resource
    private CmsSysPermissionMapper cmsSysPermissionMapper;

    @Override
    public List<CmsSysPermission> getPermissionTree() {
        QueryWrapper<CmsSysPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("isActive", true);// 数据查询条件筛选
        // 所有权限菜单数据
        List<CmsSysPermission> menuNotList = cmsSysPermissionMapper.selectList(wrapper);
        // 权限菜单parentId=0的数据
        List<CmsSysPermission> menuList = menuNotList.stream().filter(p -> p.getParentId() == 0).collect(Collectors.toList());
        getTree(menuList, menuNotList);
        return menuList;
    }

    /**
     * 构造权限树结构
     * @param menuList 最上级权限菜单数据 即 parentId=0
     * @param menuNotList 所有权限菜单数据
     * @return
     */
    public List<CmsSysPermission> getTree(List<CmsSysPermission> menuList, List<CmsSysPermission> menuNotList){
        for(CmsSysPermission p:menuList){
            List<CmsSysPermission> menus = permissionsTree(menuNotList, String.valueOf(p.getPermsId()));
            p.setChildren(menus);
        }
        return menuList;
    }

    /**
     * 权限菜单递归
     * @param permissionList 所有权限数据
     * @param parentId 上级id
     * @return
     */
    public List<CmsSysPermission> permissionsTree(List<CmsSysPermission> permissionList, String parentId){
        List<CmsSysPermission> listMenus = new ArrayList<>();
        for (CmsSysPermission p:permissionList) {
            // 主键id
            String id = String.valueOf(p.getPermsId());
            // 上级主键parentId
            String pid = String.valueOf(p.getParentId());
            if (StringUtils.isNotEmpty(pid)){
                // 匹配当前id是否和parentId相等 即 当前数据是否为parent数据的下级
                if (pid.equals(parentId)){
                    // 递归查找当前数据是否还存在下级数据
                    List<CmsSysPermission> list = permissionsTree(permissionList, id);
                    p.setChildren(list);
                    listMenus.add(p);
                }
            }
        }
        return listMenus;
    }
}
